package cn.chenfyuan.demoapplication.controller;

import cn.chenfyuan.demoapplication.data.Response;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller
public class LoginController {
    /**
     * 登录页面
     *
     * @return
     */
    @GetMapping("/login")
    public ModelAndView login() {
        ModelAndView mav = new ModelAndView("/login");
        mav.addObject("msg", "hello-world");
        return mav;
    }

    /***
     *  post登录
     * @author linweijian
     * @Date 2018/9/3 22:13
     ** @param username
     * @param password
     * @return java.lang.String
     * @throws
     **/
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Response login(String username, String password) {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                username,
                password);
        //进行验证，这里可以捕获异常，然后返回对应信息
        subject.login(usernamePasswordToken);
        return new Response().success();
    }

    @RequestMapping(value = "/index")
    public String index() {
        return "/home";
    }

    /***
     * 退出登录
     * @author linweijian
     * @Date 2018/9/3 22:13
     ** @param
     * @return java.lang.String
     * @throws
     **/
    @RequestMapping(value = "/logout")
    public String logout() {
        return "logout";
    }

    //错误页面展示
    @RequestMapping(value = "/error", method = RequestMethod.POST)
    public String error() {
        return "error ok!";
    }

    //数据初始化
    @RequestMapping(value = "/addUser")
    public String addUser(@RequestBody Map<String, Object> map) {
        return null;
    }

    //角色初始化
    @RequestMapping(value = "/addRole")
    public String addRole(@RequestBody Map<String, Object> map) {
        return null;
    }

    //注解的使用
    @RequiresRoles("admin")
    @RequiresPermissions("create")
    @RequestMapping(value = "/create")
    public String create() {
        return "Create success!";
    }

}
